﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;

namespace XCBPM.Mobile.BLL
{
    public class ProcessMobileRequest
    {
        private string CurrentDomainUid;

        public ProcessMobileRequest()
        {

        }

        public ProcessMobileRequest(string currentuserid)
        {

        }

        /// <summary>
        private string GetDynamicHtml(XmlDocument doc, string root, string html, string nodeName, string rowTemplateHtml)
        {
            StringBuilder builder = new StringBuilder();
            List<string> list = new List<string>();
            Regex regex = new Regex(@"\{\#(?<name>.*?)\#\}", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            foreach (Match match in regex.Matches(rowTemplateHtml))
            {
                list.Add(match.Groups["name"].ToString());
            }
            XmlNode node = doc.SelectSingleNode(root + nodeName);
            if (node != null)
            {
                int num = 1;
                foreach (XmlNode node2 in node.ChildNodes)
                {
                    string str = rowTemplateHtml;
                    foreach (string str2 in list)
                    {
                        if (str2 == "&RowIndex&")
                        {
                            str = str.Replace("{#&RowIndex&#}", num++.ToString());
                        }
                        else
                        {
                            string oldValue = string.Format("{{#{0}#}}", str2);
                            string str4 = str2;
                            string str5 = string.Empty;
                            XmlNode node3 = null;
                            //处理HTML中[text][*]等特殊符号
                            if (Regex.IsMatch(str2, @"\[.*?\].+"))
                            {
                                Match match = Regex.Match(str2, @"\[(?<type>.*?)\](?<name>.+)");
                                str4 = match.Groups["name"].Value;
                                str5 = match.Groups["type"].Value;
                                if (string.IsNullOrEmpty(str5))
                                {
                                    str5 = "money";
                                }
                                node3 = node2.SelectSingleNode(str4);
                                string attribute = string.Format(" style=\"width:165px;{0}\" ", "");
                                if (node3 != null)
                                {
                                    str = str.Replace(oldValue, this.BuildControls(node3, str5, attribute, true));
                                    //str = str.Replace(oldValue, node3.InnerText);
                                }
                                else
                                {
                                    str = str.Replace(oldValue, string.Empty);
                                }
                            }
                            else
                            {
                                node3 = node2.SelectSingleNode(str2);
                                if (node3 != null)
                                {
                                    str = str.Replace(oldValue, node3.InnerText);
                                }
                                else
                                {
                                    str = str.Replace(oldValue, string.Empty);
                                }
                            }
                        }
                    }
                    builder.Append(str);
                }
            }
            return builder.ToString();
        }

        private string BuildControls(XmlNode controlsNode, string type, string attribute, bool isReadonly)
        {
            string str = string.Empty;
            string name = controlsNode.Name;
            StringBuilder builder = new StringBuilder(attribute);
            if (!Regex.IsMatch(builder.ToString(), @"xmlNode\s*?=", RegexOptions.IgnoreCase))
            {
                builder.AppendFormat(" xmlNode=\"{0}\" ", name);
            }
            builder.AppendFormat(" remark=\"{0}\"", "control");
            if (type.IndexOf("|") > 0)
            {
                string[] strArray = type.Split(new char[] { '|' });
                type = strArray[0];
                for (int i = 1; i < strArray.Length; i++)
                {
                    builder.AppendFormat(" {0} ", strArray[i]);
                }
            }
            switch (type.ToLower())
            {
                case "select":
                    builder.Append(" stamp=\"select\" ");
                    if (isReadonly)
                    {
                        builder.Append(" disabled=\"disabled\" ");
                    }
                    str = this.BuildSelect(controlsNode, builder.ToString());
                    break;

                case "checkbox":
                    {
                        builder.Append(" stamp=\"checkbox\" ");
                        string checkboxAttr = string.Empty;
                        if (isReadonly)
                        {
                            checkboxAttr = " onclick=\"return false\" ";
                        }
                        str = this.BuildCheckBox(controlsNode, builder.ToString(), checkboxAttr);
                        break;
                    }
                case "money":
                    {
                        builder.Append(" stamp=\"money\" ");
                        if (isReadonly)
                        {
                            builder.Append(" readonly=\"true\" ");
                        }
                        string subjoinStyle = " style=\"width:100%;border-top:0px;border-left:0px;border-right:0px;\" ";
                        builder = new StringBuilder(this.BuildStyle(builder.ToString(), subjoinStyle));
                        builder.Append(" class=\"easyui-numberbox\" precision=\"2\" ");
                        str = this.BuildTextBox(controlsNode, builder.ToString());
                        break;
                    }
                case "text":
                    {
                        builder.Append(" stamp=\"text\" type=\"text\" ");
                        if (isReadonly)
                        {
                            builder.Append(" readonly=\"true\" ");
                        }
                        string str5 = " style=\"width:100%;border-top:0px;border-left:0px;border-right:0px;\" ";
                        builder = new StringBuilder(this.BuildStyle(builder.ToString(), str5));
                        str = this.BuildTextBox(controlsNode, builder.ToString());
                        break;
                    }

                case "link":
                    str = this.BuildLinkWithDetail(controlsNode, builder.ToString());
                    break;

                case "linkwithprocess":
                    str = this.BuildLinkWithProcess(controlsNode, builder.ToString());
                    break;
            }
            return str.ToString();
        }

        private string BuildLinkWithDetail(XmlNode controlsNode, string attribute)
        {
            StringBuilder builder = new StringBuilder();
            string str = string.Empty;
            int result = 0;
            Match match = Regex.Match(attribute, "\\bsrc\\s*=\\s*\"(?<src>[^\"]*)\"", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            if (match.Success)
            {
                str = match.Groups["src"].Value;
            }
            Match match2 = Regex.Match(attribute, "\\bxmlNode\\s*=\\s*\"(?<xmlNode>[^\"]*)\"", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            if (match2.Success)
            {
                string str2 = match2.Groups["xmlNode"].Value;
                if (str2.IndexOf("#") > 0)
                {
                    string[] strArray = str2.Split(new char[] { '#' });
                    int.TryParse(strArray[strArray.Length - 1], out result);
                }
            }
            if (!string.IsNullOrEmpty(str))
            {
                string key = string.Empty;
                if (controlsNode != null)
                {
                    //key = string.Format("{0}_{1}_{2}_Xml", this.flowInfo.ID, controlsNode.Name, result);
                    if (HttpRuntime.Cache.Get(key) == null)
                    {
                        HttpRuntime.Cache.Insert(key, controlsNode);
                    }
                }
                str = string.Format("{0}?cachekey={1}", str, key);
                builder.AppendFormat("<a href='{0}' target='_blank'>详细信息</a>", str);
            }
            return builder.ToString();
            return string.Empty;
        }

        private string BuildLinkWithProcess(XmlNode controlsNode, string attribute)
        {
            StringBuilder builder = new StringBuilder();
            string str = "../../../Workflow/ApprovalView.aspx";
            List<int> list = new List<int>();
            string[] strArray = controlsNode.InnerText.Split(new char[] { ',' });
            foreach (string str2 in strArray)
            {
                int num;
                if (int.TryParse(controlsNode.InnerText, out num))
                {
                    list.Add(num);
                }
            }
            Match match = Regex.Match(attribute, "\\bsrc\\s*=\\s*\"(?<src>[^\"]*)\"", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            if (match.Success)
            {
                str = match.Groups["src"].Value;
            }
            foreach (int num2 in list)
            {
                //IFlowInst inst = BPMModelManager.FlowInstDAO.RetrieveInstance(num2);
                //if (inst != null)
                //{
                //    str = string.Format("{0}?procInstID={1}", str, num2);
                //    string sTopic = "";
                //    sTopic = inst.Topic.Replace("请审批", "");
                //    //builder.AppendFormat("<a href='{0}' target='_blank'>{1}</a><br />", str, sTopic);
                //    builder.AppendFormat("<a href=\"javascript:void(0)\" onclick=\"javascript:ApproveDetail.linkToFlow('{0}')\">{1}</a><br />", num2, sTopic);
                //}
            }
            return builder.ToString();

            return string.Empty;
        }

        private string BuildSelect(XmlNode controlsNode, string attribute)
        {
            StringBuilder builder = new StringBuilder();
            string name = controlsNode.Name;
            StringBuilder builder2 = new StringBuilder(attribute);
            string str2 = controlsNode.Name;
            string str3 = string.Format(" xmlNode={0} ", str2);
            Match match = Regex.Match(attribute, "xmlNode\\s*?=\\s*?\"(?<text>[^\\s\"]*)\"");
            if (match.Success)
            {
                str3 = match.Value;
                str2 = match.Groups["text"].Value;
            }
            string[] strArray = new string[] { "" };
            if (controlsNode.InnerText.IndexOf('|') > 0)
            {
                strArray = controlsNode.InnerText.Split(new char[] { '|' });
            }
            else if (controlsNode.InnerText.IndexOf(',') > 0)
            {
                strArray = controlsNode.InnerText.Split(new char[] { ',' });
            }
            int result = 0;
            if (controlsNode.Name.IndexOf('_') > 0)
            {
                string[] strArray2 = controlsNode.Name.Split(new char[] { '_' });
                if (!string.IsNullOrEmpty(strArray2[0]))
                {
                    XmlNode node = controlsNode.ParentNode.SelectSingleNode(strArray2[0]);
                    if (node != null)
                    {
                        //set the default value for mm19 mm62
                        if (strArray2[0] == "ZBIAO" && node.InnerText == "-")
                        { node.InnerText = "2"; }
                        //set the default value for mm17 mm63
                        if (strArray2[0] == "STATUS" && node.InnerText == "-")
                        { node.InnerText = "1"; }
                        int.TryParse(node.InnerText, out result);
                    }
                }
            }
            if ((result < 0) || (result > strArray.Length))
            {
                result = 0;
            }
            bool flag = false;
            int num2 = 1;
            for (int i = 0; i < strArray.Length; i++)
            {
                if (!string.IsNullOrEmpty(strArray[i]))
                {
                    string str4 = string.Empty;
                    if (result == (i + 1))
                    {
                        flag = true;
                        str4 = " selected=\"selected\" ";
                        return strArray[i];
                    }
                    //builder.AppendFormat("<option value=\"{3}\" name =\"{2}\" {4} {1}>{0}</option>", new object[] { strArray[i], str4, name, num2++, str3 });
                }
            }
            if (builder.Length > 0)
            {
                string str5 = string.Empty;
                if (!flag)
                {
                    str5 = "<option value=\"-1\">请选择</option>";
                }
                builder = new StringBuilder(string.Format("{0}{1}{2}", string.Format("<select id=\"Select{0}\" {1}>", str2, builder2.ToString()), str5, builder.ToString()));
                builder.Append("</select>");
            }
            return builder.ToString();
        }

        private string BuildStyle(string intrinsicStyle, string subjoinStyle)
        {
            string input = intrinsicStyle.Trim();
            string str2 = subjoinStyle.Trim();
            if (string.IsNullOrEmpty(str2))
            {
                return input;
            }
            Regex regex = new Regex("style\\s*=\\s*\"(?<style>[^\"]+)\"", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            if (regex.IsMatch(str2))
            {
                str2 = regex.Match(str2).Groups["style"].Value;
            }
            if (regex.IsMatch(input))
            {
                Match match = regex.Match(input);
                string str3 = match.Groups["style"].Value.Trim();
                if (!string.IsNullOrEmpty(str3))
                {
                    return input.Replace(str3, str3 + str2);
                }
                return input.Replace(match.Value, string.Format(" style = \" {0}\" ", str2));
            }
            return (input + string.Format(" style = \" {0}\" ", str2));
        }

        private string BuildTextBox(XmlNode controlsNode, string attribute)
        {
            StringBuilder builder = new StringBuilder();
            string name = controlsNode.Name;
            string str2 = controlsNode.InnerText.Trim();
            if (str2 == "......")
            {
                str2 = string.Empty;
            }
            builder.AppendFormat("<input id=\"{0}\" type=\"text\" name = \"{0}\" value=\"{1}\" {2} />", name, str2, attribute);
            return builder.ToString();
        }

        private string BuildCheckBox(XmlNode controlsNode, string divAttr, string checkboxAttr)
        {
            StringBuilder builder = new StringBuilder();
            string name = controlsNode.Name;
            StringBuilder builder2 = new StringBuilder(this.BuildStyle(divAttr, "style=\"width:100%;\""));
            string str2 = controlsNode.Name;
            string str3 = string.Format(" xmlNode={0} ", str2);
            Match match = Regex.Match(divAttr, "xmlNode\\s*?=\\s*?\"(?<text>[^\\s\"]*)\"");
            if (match.Success)
            {
                str3 = match.Value;
                str2 = match.Groups["text"].Value;
            }
            string[] strArray = new string[1];
            string innerText = controlsNode.InnerText;
            if (!string.IsNullOrEmpty(innerText))
            {
                if (innerText.IndexOf('|') > 0)
                {
                    strArray = innerText.Split(new char[] { '|' });
                }
                else if (innerText.IndexOf(',') > 0)
                {
                    strArray = innerText.Split(new char[] { ',' });
                }
            }
            List<string> list = new List<string>();
            foreach (string str5 in strArray)
            {
                if (!string.IsNullOrEmpty(str5))
                {
                    list.Add(str5);
                }
            }
            bool flag = false;
            string[] strArray2 = null;
            if (controlsNode.Name.IndexOf('_') > 0)
            {
                string[] strArray3 = controlsNode.Name.Split(new char[] { '_' });
                if (!string.IsNullOrEmpty(strArray3[0]))
                {
                    XmlNode node = controlsNode.ParentNode.SelectSingleNode(strArray3[0]);
                    if (node != null)
                    {
                        string s = node.InnerText;
                        if (s.IndexOf('|') > 0)
                        {
                            strArray2 = node.InnerText.Split(new char[] { '|' });
                            flag = true;
                        }
                        else if (s.IndexOf('&') > 0)
                        {
                            strArray2 = node.InnerText.Split(new char[] { '&' });
                            flag = true;
                        }
                        else
                        {
                            int num;
                            if (int.TryParse(s, out num))
                            {
                                strArray2 = new string[] { num.ToString() };
                                flag = true;
                            }
                        }
                    }
                }
            }
            int result = 1;
            string attribute = this.GetAttribute("br", builder2.ToString());
            if (!string.IsNullOrEmpty(attribute))
            {
                int.TryParse(attribute, out result);
            }
            for (int i = 0; i < list.Count; i++)
            {
                int num4 = i + 1;
                StringBuilder builder3 = new StringBuilder(checkboxAttr);
                builder3.Append(" style=\"vertical-align: middle;\" ");
                if (flag)
                {
                    foreach (string str8 in strArray2)
                    {
                        if (str8 == num4.ToString())
                        {
                            builder3.Append(" checked=\"checked\" ");

                            builder.AppendFormat("{0}<br />", list[i]);
                            break;
                        }
                    }
                }               
            }           
            return builder.ToString();
        }

        private string GetAttribute(string attributeName, string strAttribute)
        {
            string str = null;
            Regex regex = new Regex(string.Format("{0}\\s*=\\s*\"(?<value>[^\"]*)", attributeName), RegexOptions.Singleline | RegexOptions.IgnoreCase);
            if (regex.IsMatch(strAttribute))
            {
                str = regex.Match(strAttribute).Groups["value"].Value;
            }
            return str;
        }

        //public string GetTableHtml(string ID, bool selectType, string width, string htmlType)
        //{
        //    string templateHtml = this.GetTemplateHtml("~/Forms/FI01.html");
        //    return templateHtml;
        //}

        private string GetTemplateHtml(string path)
        {
            path = HttpContext.Current.Server.MapPath(path);
            if (!System.IO.File.Exists(path))
            {
                return string.Empty;
            }
            string str = "";
            StreamReader reader = new StreamReader(path, Encoding.GetEncoding("UTF-8"));
            try
            {
                str = reader.ReadToEnd();
            }
            finally
            {
                reader.Dispose();
                reader.Close();
            }
            return str;
        }

        public string GetHostUrl()
        {
            String path = HttpContext.Current.Request.Url.Scheme + "://" +
            HttpContext.Current.Request.Url.Authority +
            (HttpContext.Current.Request.ApplicationPath == "/" ? "" : HttpContext.Current.Request.ApplicationPath);
            return path;
        }
    }
}